package com.zgs.mall.cart.controller;

import com.zgs.mall.cart.service.CartService;
import com.zgs.mall.cart.vo.Cart;
import com.zgs.mall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartService cartService;
    //获取当前用户的购物项
    @GetMapping("userCartItems")
    public List<CartItem> getUserCartItems(){

        return cartService.getUserCartItems();
    }

    /**
     *  redirectAttributes.addFlashAttribute()将数据放在session中，只能用一次
     *  redirectAttributes.addAttribute("skuId",skuId);//会自动在url后面携带参数
     * @param skuId
     * @param num 数量
     * @param redirectAttributes
     * @return
     */
    //添加购物车
    @GetMapping("addToCart")
    public  String addToCart(@RequestParam  Long skuId,
                             @RequestParam Integer num, RedirectAttributes redirectAttributes){
       CartItem item= cartService.addToCart(skuId,num);

        redirectAttributes.addAttribute("skuId",skuId);//会自动在url后面携带参数
        return "redirect:http://cat.mall.com/addToCartSuccess.html";
    }

    //添加成功跳转
    @GetMapping("addToCartSuccess.html")
    public  String addToCartSuccess(@RequestParam Long skuId,Model model){
        //获取购物项
        CartItem item = cartService.getCattItem(skuId);
        model.addAttribute("item",item);
        return "success";
    }
    //获取购物车.
    @GetMapping("getCartList")
    public String getCartList(Model model){
        Cart cart = cartService.getCartList();
        model.addAttribute("cart",cart);
        return "cartList";
    }

    /**
     * 选中购物项
     * @param itemId
     * @param check 1是选中 2是没有选中
     * @return
     */
    @RequestMapping("checkItem")
    public String checkItem(@RequestParam  Long itemId,@RequestParam Integer check){
        cartService.checkItem(itemId,check);
        return "redirect:http://cat.mall.com/getCartList";
    }
    //购物项增加减少
    @RequestMapping("countItem")
    public String countItem(@RequestParam  Long itemId,@RequestParam Integer num){
        cartService.countItem(itemId,num);
        return "redirect:http://cat.mall.com/getCartList";
    }
}
